package com.hopscotch.service.impl;

import com.hopscotch.entity.User;
import com.hopscotch.mapper.UserDetailsMapper;
import com.hopscotch.mapper.UserMapper;
import com.hopscotch.service.UserService;
import com.hopscotch.utils.JwtUtils;
import com.hopscotch.utils.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.security.core.Authentication;

import java.util.HashMap;
import java.util.HashSet;
import java.util.UUID;

@Service
public class UserServiceImpl implements UserService {
    //认证管理对象，在Security配置类中进行配置，用于自动调用实现好的UserDetailsService接口
    @Autowired
    private AuthenticationManager authenticationManager;
    @Autowired
    private JwtUtils jwtUtils;

    @Autowired
    private UserMapper userMapper;
    //进行用户认证的代码
    @Override
    public String userLogin(User userLogin) {
        Authentication authentication = null;
        try {
            // 该方法会去调用UserDetailsServiceImpl.loadUserByUsername
            authentication = authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(userLogin.getUserName(), userLogin.getUserPassword()));
        } catch (Exception e) {
            if (e instanceof BadCredentialsException) {
                throw new RuntimeException("用户认证失败");
            } else {
                throw new RuntimeException(e.getMessage());
            }
        }
        //创建token令牌
        HashMap<String, Object> map = new HashMap<>();
        String uid = UUID.randomUUID().toString().replace("-", "");
        map.put("uid",uid);
        map.put("username", authentication.getName());
        HashSet<String> set = new HashSet<>();
        //将权限还原成String类型的集合
        authentication.getAuthorities().forEach(auth -> {
            set.add(auth.getAuthority());
        });
        map.put("perms", set);
        String token = jwtUtils.creatToken(map);
        jwtUtils.saveToken(token);
        return token;
    }

    @Override
    public User getAttendance() {
        String currentUserName = SecurityUtils.getCurrentUserName();
        User user = userMapper.getAttendance(currentUserName);
        return user;
    }

}
